<template>
  <div>
    <Menu menuActive="/download" />
    <layout>
      <template v-slot:main>
        <el-row :gutter="20">
          <el-col :lg="18" style="margin-bottom: 20px;">
            <div class="form_container height_light_bgcolor">
              <h1 style="font-weight:700;font-size:20px;margin-bottom: 20px;margin-top: 10px;">上传资源</h1>
              <el-form ref="ruleFormRef" status-icon :rules="rules" label-width="80px" :size="formSize"
                :model="ruleForm">
                <el-form-item prop="url" label="资源">
                  <el-upload class="upload-demo" drag style="width:100%" :headers="headers" :action="uploadUrl"
                    :on-error="handleUploadError" :before-upload="handleBeforeUpload" :on-exceed="handleExceed"
                    :file-list="ruleForm.url" :limit="1" :on-success="handleUploadSuccess" ref="fileUpload"
                    :on-remove="handleDelete">
                    <el-icon class="el-icon--upload">
                      <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                      拖拽文件到此 或者 <em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        请上传 大小不超过 <span style="color:red">5MB</span> 格式为 <span
                          style="color:red">doc/xls/txt/pdf/zip/rar/7z</span> 的文件
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
                <el-form-item label="资源标题" prop="title">
                  <el-input v-model="ruleForm.title" />
                </el-form-item>
                <el-form-item label="资源描述" prop="description">
                  <el-input :rows="2" type="textarea" v-model="ruleForm.description" />
                </el-form-item>
                <el-form-item label="方向" prop="directionId">
                  <el-select v-model="ruleForm.directionId" placeholder="请选择方向">
                    <el-option v-for="item in directOptions" :key="item.value" :label="item.label"
                      @change="handleChangeDirect" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button style="width: 300px;" type="primary" @click="submitForm(ruleFormRef)"
                    :loading="loadingbtn">提交</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col :lg="6">
            <div class="adv_container height_light_bgcolor">
              <div class="tips">
                资源上传下载等过程中有任何疑问或建议，欢迎提出宝贵意见哦~我们会及时处理！
                <a href="https://support.qq.com/product/426248" target="_blank">
                  <el-button type="primary" link>点击此处反馈</el-button>
                </a>
              </div>
              <div class="adv_pic_wrap">
                <img src="@/assets/images/upload-pic.png" alt="">
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
  </div>
</template>

<script lang="ts" setup>
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import Avatar from '@/components/Avatar/index.vue'
import {
  Tickets,
  UserFilled,
  RefreshLeft,
  Plus,
  Document,
  User,
  ChatDotSquare,
  View,
  Timer,
  Pointer,
  More,
  Location,
  Link,
  OfficeBuilding,
  UploadFilled
} from '@element-plus/icons-vue'
import { onMounted, ref, getCurrentInstance, reactive } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadFile } from 'element-plus'
import { getDirection } from '@/api/dictionary'
import { uploadResource } from '@/api/download'
import router from '@/router'
import { sizeTostr } from '@/utils'
const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/common/upload` // 上传的图片服务器地址
const headers = {
  Authorization: localStorage.getItem('token'),
}
const directOptions = ref<any>([])
const formSize = ref('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<any>({
  title: '',
  description: '',
  directionId: '',
  url: [],
  contentLength: 0
})
const loadingbtn = ref<boolean>(false)
const fileUpload = ref<null | HTMLElement>(null)
const rules = reactive<FormRules>({
  url: [
    {
      required: true, message: '请上传资源', trigger: 'blur'
    }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 50, message: '资源标题字数只能在1~50之间', trigger: 'blur' },
  ],
  directionId: [
    {
      required: true,
      message: '请选择方向',
      trigger: 'blur',
    },
  ],
})
const handleChangeDirect = (value: number) => {
  console.log(value);
}
const handleBeforeUpload = (file: any): boolean => {
  let fileType = ['doc', 'xls', 'txt', 'pdf', 'zip', 'rar', '7z']
  let fileSize = 5
  // 校检文件类型
  if (fileType) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1]
    const isTypeOk = fileType.indexOf(fileExt) >= 0
    if (!isTypeOk) {
      ElMessage({
        message: `文件格式不正确, 请上传${fileType.join('/')}格式文件!`,
        type: 'error',
        duration: 2 * 1000
      })
      return false
    }
  }
  const sizeKB = file.size / 1024
  // 校检文件大小
  if (fileSize) {
    const isLt = sizeKB / 1024 < fileSize
    if (!isLt) {
      ElMessage({
        message: `上传文件大小不能超过 ${fileSize} MB!`,
        type: 'error',
        duration: 2 * 1000
      })
      return false
    }
  }
  return true
}
// 删除文件
function handleDelete(file: UploadFile) {
  const findex = ruleForm.url.map((f: { name: string; }) => f.name).indexOf(file.response?.fileName);
  if (findex > -1) {
    ruleForm.url.splice(findex, 1);
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  // console.log(ruleForm);
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        loadingbtn.value = true
        // console.log(ruleForm);
        let url = ''
        if (ruleForm.url) {
          url = ruleForm.url[0].name
        }
        const res: any = await uploadResource({ ...ruleForm, url })
        if (res) {
          ElMessage({
            message: "提交成功",
            type: 'success',
            duration: 2 * 1000
          })
          location.reload()
        }
      } finally {
        loadingbtn.value = false
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const getDirectOptionsData = async () => {
  const { data }: any = await getDirection()
  directOptions.value = data.map((item: { id: number; name: string; }) => ({ value: item.id, label: item.name }))
  // console.log(directOptions.value);
}
// 上传失败
const handleUploadError = () => {
  ElMessage({
    message: "上传图片失败，请重试",
    type: 'error',
    duration: 2 * 1000
  })
}
const handleExceed = () => {
  ElMessage({
    message: `上传文件数量不能超过 1 个!`,
    type: 'error',
    duration: 2 * 1000
  })
}
const handleUploadSuccess = (res: any, file: any) => {
  if (res.code !== 200) {
    fileUpload.value?.handleRemove(file);
    if (res.code === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessageBox.confirm(
        '登录超时或者未登陆，您可以继续停留在该页面或者重新登录',
        '提示',
        {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        router.push('/login')
      })
    }
    return
  }
  ruleForm.contentLength = file.size
  uploadedSuccessfully(res);
}
const uploadedSuccessfully = (res: any) => {

  ruleForm.url.push({ name: res.fileName, url: res.url })
}
onMounted(() => {
  getDirectOptionsData()
})
</script>

<style scoped lang="scss">
// @import '@/assets/style/reset.scss';
@import './index.scss';
</style>
